﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MultiDAQ_Analysis.Util
{
    using System;


    public static class Crc32Utils
    {
        private const uint Polynomial = 0xEDB88320;  // IEEE 802.3 反转低字节序多项式
        private const uint InitialValue = 0xFFFFFFFF;
        private const uint ValidCrcValue = 0xC704DD7B;

        /// <summary>
        /// 计算数据的 CRC32 值，返回按位取反后的 uint 值（与 Verilog 一致）
        /// </summary>
        public static uint ComputeCrcOutUInt(byte[] data)
        {
            uint crc = InitialValue;

            foreach (byte b in data)
            {
                crc ^= b;
                for (int i = 0; i < 8; i++)
                {
                    crc = (crc & 1) != 0 ? (crc >> 1) ^ Polynomial : crc >> 1;
                }
            }

            return ~crc; // 按位取反后返回
        }

        /// <summary>
        /// 返回 CRC 校验值的小端（低字节序）表示，用于网络发送
        /// </summary>
        public static byte[] GetCrcBytes(byte[] data)
        {
            uint crc = ComputeCrcOutUInt(data);
            return BitConverter.GetBytes(crc); // 默认小端格式（低位在前）
        }

        /// <summary>
        /// 接收端验证数据+CRC 后是否等于固定 magic 校验值
        /// </summary>
        public static bool ValidateCrc(byte[] dataWithCrc)
        {
            uint crc = InitialValue;

            foreach (byte b in dataWithCrc)
            {
                crc ^= b;
                for (int i = 0; i < 8; i++)
                {
                    crc = (crc & 1) != 0 ? (crc >> 1) ^ Polynomial : crc >> 1;
                }
            }

            return crc == ValidCrcValue;
        }
    }


}
